package com.bthdung.studios.lesson12.framework.buffers;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import android.opengl.GLES20;

final class BufferUtils
{
	public static FloatBuffer createFloatBuffer(float[] data)
	{
		ByteBuffer bytes = ByteBuffer.allocateDirect(data.length * 4);
		bytes.order(ByteOrder.nativeOrder());
		FloatBuffer result = bytes.asFloatBuffer();
		result.put(data);
		result.position(0);

		return result;
	}

	public static ShortBuffer createShortBuffer(short[] data)
	{
		ByteBuffer bytes = ByteBuffer.allocateDirect(data.length * 2);
		bytes.order(ByteOrder.nativeOrder());
		ShortBuffer result = bytes.asShortBuffer();
		result.put(data);
		result.position(0);

		return result;
	}
	
	public static int glGenerateVertexBuffer(FloatBuffer buffer)
	{
		int[] id = new int[1];		
		GLES20.glGenBuffers(1, id, 0);

		GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, id[0]);
		GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, (Float.SIZE / 8) * buffer.capacity(), buffer, GLES20.GL_STATIC_DRAW);

		
		GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
		GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
		
		return id[0];
	}
	
	public static int glGenerateIndexBuffer(ShortBuffer buffer)
	{
		int[] id = new int[1];
		GLES20.glGenBuffers(1, id, 0);

		GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, id[0]);
		GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, (Short.SIZE / 8) * buffer.capacity(), buffer, GLES20.GL_STATIC_DRAW);

		GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
		GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
		
		return id[0];
	}
}
